package com.gxinyu.needle

import androidx.annotation.MainThread
import androidx.lifecycle.*
import kotlin.reflect.KClass

/**
 * @author gxinyu
 * @date  2022/5/8
 * @desc  扩展BaseFragment的ViewModel
 */

@MainThread
public inline fun <reified VM : ViewModel> BaseFragment<*, *>.createViewModel(
    noinline ownerProducer: () -> ViewModelStoreOwner = { this },
    noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null,
): Lazy<VM> = createModelLazy(VM::class, { ownerProducer().viewModelStore }, factoryProducer)


@MainThread
public fun <VM : ViewModel> BaseFragment<*, *>.createModelLazy(
    viewModelClass: KClass<VM>,
    storeProducer: () -> ViewModelStore,
    factoryProducer: (() -> ViewModelProvider.Factory)? = null,
): Lazy<VM> {
    val factoryPromise = factoryProducer ?: {
        defaultViewModelProviderFactory
    }
    return ViewModelLazy(viewModelClass, storeProducer, factoryPromise)
}